package cn.lanqiao.springboot.controller;

import cn.lanqiao.springboot.entity.User;
import cn.lanqiao.springboot.service.UserService;
import cn.lanqiao.springboot.util.CurrentUserUtil;
import cn.lanqiao.springboot.util.DesUtil;
import cn.lanqiao.springboot.util.EmailSenderUtil;
import cn.lanqiao.springboot.util.Result;
import cn.lanqiao.springboot.vo.QueryUserVO;
import cn.lanqiao.springboot.vo.UserVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.validation.Valid;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    EmailSenderUtil emailSenderUtil;

    @Value("${spring.mail.key}")
    String key;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/list")
    public Result getUsers(@RequestBody QueryUserVO queryUserVO) {
        // 这里可以调用 UserService 来获取用户数据
        PageHelper.startPage(queryUserVO.get_page(), queryUserVO.get_limit());
        List<User> users = userService.getAllUsers(queryUserVO);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return Result.success(pageInfo);
    }

    @GetMapping("/query/{userId}")
    public Result getUser(@PathVariable("userId") Integer id) {
        QueryUserVO queryUserVO = new QueryUserVO();
        return Result.success(queryUserVO);
    }

    @PostMapping("/insert")
    public Result insertUser(@RequestBody User user) {
        try {
            user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
            userService.insertUser(user);
            return Result.success();
        } catch (Exception e) {
            return Result.fail(500, "用户名已存在");
        }
    }

    @DeleteMapping("/delete/{userId}")
    public Result deleteUser(@PathVariable("userId") Integer userId) {
        userService.deleteUser(userId);
        return Result.success();
    }

    @PutMapping("/update")
    public Result updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success();
    }

    @PostMapping("/login")
    public Result checkUser(@Valid @RequestBody User user) {
        UserVO foundUser = userService.checkUser(user);
        if (foundUser != null) {
            //密码验证
            if (!BCrypt.checkpw(user.getPassword(), foundUser.getPassword())) {
                return Result.fail(402, "密码错误！");
            }
            //签发无状态JWT
//            String token = JWT.create()
//                    .withClaim("userId", foundUser.getUserId())//jwt中存用户id
//                    .withClaim("userName", foundUser.getUserName())//jwt中存用户名
//                    .withClaim("roleId", foundUser.getRoleId())//jwt中存用户id
//                    .withClaim("roleName", foundUser.getRoleName())//jwt中存用户名
//                    .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60))//设置失效时间一小时
//                    .sign(Algorithm.HMAC256("david"));//设置秘钥。
            //有状态的JWT
//            System.currentTimeMillis();
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForHash().put("user_token", token, foundUser);
            return Result.success(token);
        } else {
            return Result.fail(401, "用户名不存在！");
        }
    }

    @GetMapping("/getUserInfo")
    public Result getUserInfo() {
        return Result.success((UserVO) CurrentUserUtil.get());
    }

    /**
     * ------------- 手机验证 -------------
     * 一个发送验证码
     * 一个验证验证码
     * ------------- 手机验证 -------------
     */

    @GetMapping("/sendCode/{phone}")
    public Result sendCode(@PathVariable("phone") String phone) {
        //1. 生成随机验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        //2. 存入redis，设置过期时间为2分钟
        redisTemplate.opsForValue().set("code:" + phone, code,1, TimeUnit.MINUTES);
        //3. 调用第三方短信服务商API发送短信
        System.out.println("手机号：" + phone + "，验证码：" + code);
        return Result.success();
    }

    @PostMapping("/verifyCode")
    public Result verifyCode(@RequestParam("phone") String phone, @RequestParam("code") String code) {
        //1. 从redis中获取验证码
        String redisCode = (String) redisTemplate.opsForValue().get("code:" + phone);
        //2. 验证码比对
        if (redisCode != null && redisCode.equals(code)) {
            return Result.success();
        } else {
            return Result.fail(501, "验证码错误或已过期");
        }
    }

    @PostMapping("/emailLogin")
    public Result login(@RequestBody User user) {
        //注册用户
        //userService.insertUser(user);
        //发送邮件
        //emailSenderUtil.sendEmail(user.getUserName());
        //消息队列发送-生产者
        rabbitTemplate.convertAndSend("emailQueue", user.getUserName());
        return Result.success();
    }

    @GetMapping("/activation/{code}")
    public Result login(@PathVariable String code) {
        return Result.success(DesUtil.decrypt(code,key));
    }
}
